package com.example.usercenter.service.impl;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.usercenter.Exception.BusinsessException;
import com.example.usercenter.common.BaseResponse;
import com.example.usercenter.common.ErrorCode;
import com.example.usercenter.common.ResultUtils;
import com.example.usercenter.service.UserService;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.mapper.UserMapper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.example.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.example.usercenter.constant.UserConstant.USERLOGINSTATUS;

/**
* @author asus
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-12-21 16:20:42
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    /**
     * 加密盐值
     */
    private static final String SALT = "XY";
    /**
     * 设置用户登录状态键值
     */

    @Resource
    private UserMapper userMapper;
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
        //校验
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinsessException(ErrorCode.NULL_ERROR,"请求参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"账户过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"密码过短或校验码过短");
        }
        if (planetCode.length() < 5){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"星球密码过短");
        }
        //账户是否重复
        //检查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = this.count(queryWrapper);
        if (count>0){
            return -1;
        }

        //校验星球账户是否重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        count = this.count(queryWrapper);
        if (count>0){
            return -1;
        }
        //校验账户不包含特殊字符

        //密码和校验密码相同
        if (userPassword == checkPassword){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"密码和校验密码相同");
        }

        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPassword);
        int insert = userMapper.insert(user);
        //boolean save = this.save(user);
        return 0;
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @return
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinsessException(ErrorCode.NULL_ERROR,"账号或密码为空");
        }
        if (userAccount.length() < 4){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"账户过短");
        }
        if (userPassword.length() < 8){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",newPassword);
        User one = userMapper.selectOne(queryWrapper);
        if (one == null){
            log.info("user login failed");
        }
        //用户脱敏，创建一个新User对象，将想要返回给前端的信息封装返回。（这里屏蔽了Password）
        User saftuser = saftUser(one);
        //设置Session
        request.getSession().setAttribute(USERLOGINSTATUS,saftuser);
        return saftuser;
    }

    @Override
    public List<User> searchUsers(String userName) {
        if (userName == null){
            throw new BusinsessException(ErrorCode.NULL_ERROR,"");
        }
        QueryWrapper query = new QueryWrapper();
        query.eq("username",userName);
        List list = userMapper.selectList(query);
        return list;
    }
    public User saftUser(User one){
        User saftuser = new User();
        saftuser.setId(one.getId());
        saftuser.setUserAccount(one.getUserAccount());
        saftuser.setUsername(one.getUsername());
        saftuser.setAvatarUrl(one.getAvatarUrl());
        saftuser.setGender(one.getGender());
        saftuser.setPhone(one.getPhone());
        saftuser.setEmail(one.getEmail());
        saftuser.setUserStatus(one.getUserStatus());
        saftuser.setCreateTime(new Date());
        saftuser.setUpdateTime(new Date());
        saftuser.setIsDelete(0);
        saftuser.setUserrole(one.getUserrole());
        saftuser.setPlanetCode(one.getPlanetCode());
        return saftuser;
    }

    public List<User> searchUsesrByTags(List<String> tagNameList){
        //方法一：使用sql模糊查询
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR,"传入的标签为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for(String tagName : tagNameList){
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return users.stream().map(this::saftUser).collect(Collectors.toList());
        //方法二：基于内存查询
        /**
         * 1.查询所有用户信息
         * 2。获取用户的tags
         * 3.使用gson序列化为json格式
         * 4.查询标签中是否包含目标标签
         */
//         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        List<User> users = userMapper.selectList(queryWrapper);
//        Gson gson = new Gson();
//        return users.stream().filter(user -> {
//            String tags = user.getTags();
//            if (StringUtils.isAnyBlank(tags)){
//                return false;
//            }
//            Set<String> templist = gson.fromJson(tags,new TypeToken<Set<String>>(){}.getType());
//java8新特性
//            templist = Optional.ofNullable(templist).orElse(new HashSet<>());
//            for (String str: tagNameList) {
//                 if (!templist.contains(str)){
//                     return false;
//                 }
//            }
//            return true;
//        }).map(this::saftUser).collect(Collectors.toList());
    }
    /**
     * 修改用户个人信息
     * @return
     */
    public Integer updateUser(User user,HttpServletRequest request){
        User loginUser = getLoginUser(request);
        Integer id = user.getId();
        if (id <= 0){
            throw new BusinsessException(ErrorCode.PARAMS_ERROR);
        }else {
            User user1 = userMapper.selectById(id);
            if (isAdmin(request) || user1.getId() == loginUser.getId()){
                return userMapper.updateById(user);
            }
        }
        //修改失败
        return 0;
    }


    /**
     * 是否是管理员
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request){
        Object userLoginStatus = request.getSession().getAttribute(USERLOGINSTATUS);
        User user = (User) userLoginStatus;
        if (user == null || user.getUserrole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }

    /**
     * 获取登陆的用户
     * @param request
     * @return
     */
    public User getLoginUser(HttpServletRequest request){
        Object o = request.getSession().getAttribute(USERLOGINSTATUS);
        return (User) o;
    }
}




